package com.cskaoyan.controller.admin;

import com.cskaoyan.bean.BaseRespVo;
import com.cskaoyan.bean.PageDataVo;
import com.cskaoyan.bean.admin.Storage;
import com.cskaoyan.bean.admin.bo.StorageParamBo;
import com.cskaoyan.service.admin.StorageService;
import com.cskaoyan.utils.FileUploadUtils;
import com.cskaoyan.utils.ReflectionSetJavaBeanUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;

/**
 * 类<code>Doc</code>用于：TODO
 *
 * @author Acher
 * @version 1.0
 * @date 2021-10-19
 */
@RequestMapping("admin/storage")
@RestController
public class StorageController {

    @Autowired
    StorageService storageService;

    @RequiresPermissions("admin:storage:create")
    @PostMapping("create")
    // http://localhost:8083/admin/storage/create
    public BaseRespVo create(@RequestParam("file") MultipartFile file, HttpServletRequest req) {
        if (file.isEmpty()) return BaseRespVo.error("上传失败，请选择文件");
        // 通过file和req生成Storage实例
        Storage storage = FileUploadUtils.getStorageByFileUpload(file);
        if (!storageService.create(storage)) return BaseRespVo.error("添加失败");
        return BaseRespVo.ok(storage);
    }

    @RequiresPermissions("admin:storage:list")
    @RequestMapping("list")
    // http://localhost:8083/admin/storage/list?page=1&limit=20&sort=add_time&order=desc
    public BaseRespVo list(StorageParamBo storageParam) {
        PageDataVo pageDataVo = storageService.query(storageParam);
        return BaseRespVo.ok(pageDataVo);
    }

    @RequiresPermissions("admin:storage:update")
    @PostMapping("update")
    // http://localhost:8083/admin/storage/update
    public BaseRespVo update(@RequestBody @Validated Storage storage, BindingResult bindingResult) {
        ReflectionSetJavaBeanUtils.setJavaBean(storage);
        if (!storageService.update(storage))
            return BaseRespVo.error("修改失败");
        return BaseRespVo.ok(storage);
    }

    @RequiresPermissions("admin:storage:delete")
    @PostMapping("delete")
    // http://localhost:8083/admin/storage/delete
    public BaseRespVo delete(@RequestBody @Validated Storage storage, BindingResult bindingResult) {
        storage.setDeleted(true);
        if (!storageService.delete(storage))
            return BaseRespVo.error("修改失败");
        return BaseRespVo.ok(storage);
    }
}
